﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.Data.SqlClient;
using PominaScale.DataAccess;

namespace PominaScale
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            try
            {
                // Bool value to show this application do own Mutex.
                bool ownmutex;

                // Create and get Mutex permission is named icon;
                using (Mutex mutex = new Mutex(true, "PominaScale", out ownmutex))
                {

                    // If application own Mutex, it can go on execute;
                    // else, application exit.
                    if (ownmutex)
                    {
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Application.CurrentCulture = new System.Globalization.CultureInfo("vi-VN");

                        if (!SystemInformation.Network && !MessageBoxEx.ShowYesNoQuestion("Kết nối mạng không được tìm thấy. Bạn có muốn tiếp tục chạy chương trình cân?"))
                        {
                            return;
                        }

                        BuildConnectionString();

                        Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
                        Application.Run(FrmMDI.Instance);

                        //Dispose Mutex;
                        mutex.ReleaseMutex();
                    }
                    else
                    {
                        Console.WriteLine("Another instance of this application " +
                            " already owns the mutex named MutexERPKimTruc.");
                    }
                }
            }
            catch (AbandonedMutexException ex)
            {
                MessageBoxEx.ShowAlert("Error: " + ex.Message);
            }
        }

        static void Application_ApplicationExit(object sender, EventArgs e)
        {
            if (null != Common.Port && Common.Port.IsOpen)
            {
                Common.Port.Close();
                Common.Port.Dispose();
            }
        }

        static void BuildConnectionString()
        {
            if (string.IsNullOrEmpty(define.CONNECTIONSTRING) || !new Connection().CheckDatabases())
            {
                FrmDatabase formConfiguration = new FrmDatabase();
                if (formConfiguration.ShowDialog() == DialogResult.OK)
                {
                    if (define.WINDOWMODE)
                    {
                        // Build connection string with the window mode
                        BuildSqlConnString(define.DATABASE, define.SERVER);
                    }
                    else
                    {
                        // Build connection string without the window mode
                        BuildSqlConnString(define.DATABASE, define.SERVER, define.USERID, define.PASSWORD);
                    }

                    define.CONNECTIONSTRING = ApplicationIsolatedSettings.GetSetting("CONNECTION_STRING");
                }
            }
        }

        /// <summary>
        /// Dynamic build the connection string for db
        /// i.e. BuildEntityConnString("Pomina", "localhost", "Database.POSDB", "postgres", "postgres")
        /// Store it in ApplicationIsolatedSetting
        /// metadata=res://*/Database.KimTrucData.csdl|res://*/Database.KimTrucData.ssdl|res://*/Database.KimTrucData.msl;provider=System.Data.SqlClient;provider connection string="Data Source=kimtruc2.no-ip.info;Initial Catalog=KIMTRUCDATA;Persist Security Info=True;User ID=sa;Password=***********"
        /// </summary>
        /// <param name="dbFileName"></param>
        /// <param name="server"></param>
        /// <param name="resourceData"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        static void BuildSqlConnString(string dbFileName, string server, string username, string password)
        {
            SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();

            // Get the original string from the now public property of your tableadapter

            connectionStringBuilder.InitialCatalog = dbFileName;
            connectionStringBuilder.DataSource = server;
            connectionStringBuilder.PersistSecurityInfo = true;
            connectionStringBuilder.UserID = username;
            connectionStringBuilder.Password = password;
            // Change the database. Depending on your scenario you might need to change more

            // Return the new string, you can use it to set the connectionstring of your tableadapter

            ApplicationIsolatedSettings.Instance["CONNECTION_STRING"] = connectionStringBuilder.ToString();
        }

        /// <summary>
        /// Dynamic build the connection string for db
        /// i.e. BuildEntityConnString("Pomina", "localhost", "Database.POSDB", "postgres", "postgres")
        /// Store it in ApplicationIsolatedSetting
        /// metadata=res://*/Database.KimTrucData.csdl|res://*/Database.KimTrucData.ssdl|res://*/Database.KimTrucData.msl;provider=System.Data.SqlClient;provider connection string="Data Source=kimtruc2.no-ip.info;Initial Catalog=KIMTRUCDATA;Persist Security Info=True;User ID=sa;Password=***********"
        /// </summary>
        /// <param name="dbFileName"></param>
        /// <param name="server"></param>
        /// <param name="resourceData"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        static void BuildSqlConnString(string dbFileName, string server)
        {
            SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();

            // Get the original string from the now public property of your tableadapter

            connectionStringBuilder.InitialCatalog = dbFileName;
            connectionStringBuilder.DataSource = server;
            connectionStringBuilder.IntegratedSecurity = true;
            // Change the database. Depending on your scenario you might need to change more

            // Return the new string, you can use it to set the connectionstring of your tableadapter

            ApplicationIsolatedSettings.Instance["CONNECTION_STRING"] = connectionStringBuilder.ToString();
        }

    }
}
